import subprocess
import sys

import jenkins

BASE_URL = 'http://43.139.139.14:8080/'
USERNAME = 'admin'
PASSWORD = 'Ask@123'
PROJECT_NAME = "rockflow-android"

server = jenkins.Jenkins(BASE_URL, username=USERNAME, password=PASSWORD)


def run_git_command(command):
    result = subprocess.run(
        command.split(),  # 将命令拆分为参数列表
        stdout=subprocess.PIPE,  # 捕获标准输出
        stderr=subprocess.PIPE,  # 捕获标准错误
        text=True  # 将输出解码为文本
    )
    if result.returncode == 0:
        return result.stdout.strip()  # 返回命令输出，去除首尾空白
    else:
        print("Error:", result.stderr)
        return None


def buildApk(buildParams, notify):
    gitBranch = "origin/" + run_git_command("git rev-parse --abbrev-ref HEAD")
    region = "Domestic"
    env = "Dev"
    package = "Debug"
    if buildParams[0] == "a":
        region = "Aboard"
    if buildParams[1] == "p":
        region = "Product"
    if buildParams[1] == "r":
        region = "Release"
    parameters = {
        "branch": gitBranch,
        "packageType": "assemble",
        "region": region,
        "env": env,
        "package": package,
        "resultAction": "notify",
        "resultContent": notify
    }
    print(gitBranch + " | " + region + env + package)
    buildNumber = server.build_job(PROJECT_NAME, parameters)
    print("buildNumber: " + str(buildNumber))


class CustomError(Exception):
    def __init__(self, message):
        self.message = message


if __name__ == '__main__':
    buildType = sys.argv[1]
    print(buildType)
    if not (buildType == "ddd" or buildType == "dpd" or buildType == "dpr" or buildType == "add" or buildType == "apd"):
        raise CustomError("buildType is error")

    notify = ""
    if len(sys.argv) > 2:
        notify = sys.argv[2]

    buildApk(buildType, notify)
